﻿namespace TestApp.Client
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Media;
    using JetBrains.Annotations;

    internal sealed class ParamValueToColorConverter : IValueConverter
    {
        private static readonly Color DefaultColor = Color.FromRgb(255, 255, 255);

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Color color;
            if (!TryGetColor(value, out color))
            {
                return DependencyProperty.UnsetValue;
            }

            return new SolidColorBrush(color);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private static bool TryGetColor([CanBeNull] object value, out Color color)
        {
            if (value == null)
            {
                color = DefaultColor;
                return true;
            }

            var doubleVal = value as double?;
            if (doubleVal != null)
            {
                var val = doubleVal.Value;
                if (Math.Abs(val) < double.Epsilon)
                {
                    color = DefaultColor;
                    return true;
                }

                if (val < 0d)
                {
                    color = Color.FromScRgb((float)-val, 255f, 140f, 0f);
                    return true;
                }

                if (val > 0d)
                {
                    color = Color.FromScRgb((float)val, 0f, 0f, 0f);
                    return true;
                }
            }

            color = DefaultColor;
            return false;
        }
    }
}
